package com.ywy.service.impl;

import com.ywy.dao.MessageDao;
import com.ywy.entity.Message;
import com.ywy.service.MessageService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.List;

/**
 * 系统消息Service实现类
 *
 * @author ywy
 * @date 2023/3/25 17:54
 */
@Transactional
@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    private MessageDao messageDao;

    @Override
    public List<Message> list(Message message, Integer pageNo, Integer pageSize) {
        Pageable pageable = new PageRequest(pageNo - 1, pageSize, Sort.Direction.DESC, "publishDate");
        Page<Message> pageMessage = messageDao.findAll(createSpecification(message), pageable);
        return pageMessage.getContent();
    }

    @Override
    public long getTotal(Message message) {
        return messageDao.count(createSpecification(message));
    }

    @Override
    public int getCountByUserId(Integer userId) {
        return messageDao.getCountByUserId(userId);
    }

    @Override
    public Message save(Message message) {
        return messageDao.save(message);
    }

    @Override
    public int updateStatus(Integer userId) {
        return messageDao.updateStatus(userId);
    }

    private Specification<Message> createSpecification(Message message) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            if (message != null) {
                if (message.getUser() != null && message.getUser().getId() != null) {
                    predicate.getExpressions().add(criteriaBuilder.equal(root.get("user").get("id"), message.getUser().getId()));
                }
            }
            return predicate;
        };
    }
}
